<template>
  <view class="subject-container">
    <hi-navbar
      fixed
      transparent="show"
      :backgroundColor="[237, 240, 243]"
      title="选择试卷"
    >
    </hi-navbar>
    <div class="u-m-t-12" id="tab-wrap">
      <hi-tabs :value.sync="tabIndex" :items="tabs" @changeTab="onChangeTab">
        <template v-slot:item="{ item }">
          {{ item.label }}
        </template>
      </hi-tabs>
    </div>
    <div class="u-p-l-32 u-p-r-32 u-m-t-18 u-flex u-row-right" id="intro">
      <u-tag
        :text="subjectIntro || '---'"
        mode="dark"
        type="info"
        shape="circle"
      ></u-tag>
    </div>
    <mescroll-uni
      :top="tabTop"
      ref="mescrollRef"
      @init="mescrollInit"
      @down="downCallback"
      @up="upCallback"
      :up="upOption"
      :down="downOption"
    >
      <paper-list :paper-list="papers" @click="onClickPaper"></paper-list>
    </mescroll-uni>

    <!-- 认证弹窗 -->
    <u-popup v-model="isShowVip" mode="center" border-radius="32">
      <div class="u-flex-col u-row-center u-col-center u-p-32">
        <image
          src="/static/image/vip.svg"
          style="width: 60px; height: 60px"
        ></image>
        <div class="u-m-t-24 u-content-color">该试卷认证后即可查看</div>
        <div class="u-flex u-m-t-24 u-row-between">
          <div class="u-m-r-24">
            <u-button size="mini" @click="isShowVip = false">取 消</u-button>
          </div>
          <u-button size="mini" type="warning" @click="onClickAudit"
            >立即认证</u-button
          >
        </div>
      </div>
    </u-popup>
  </view>
</template>

<script>
import HiTabs from "_c/Tabs"
import PaperList from "./components/PaperList.vue"
import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js"

import { parseTime } from "_u/date"
import func from "_u/func"
import { mapGetters, mapActions } from "vuex"
import { wxMessageId, qqMessageId } from "@/config"

// 已审核题库
let auditPaper = []
// 选择题库
let selectPaper = null

export default {
  mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
  components: {
    HiTabs,
    PaperList,
  },
  data() {
    return {
      title: "",
      activeName: "",
      activePapers: [],
      isShowVip: false,
      subjects: [],

      // tab config
      tabTop: 300,
      preIndex: 0,
      tabs: [],
      tabIndex: 0, // 当前菜单下标

      // 刷新设置
      upOption: {
        auto: false,
      },
      downOption: {
        auto: false,
      },
    }
  },

  computed: {
    ...mapGetters("user", ["isVip", "userInfo"]),
    // 列表数据
    papers() {
      if (this.tabs[this.tabIndex]) {
        return this.tabs[this.tabIndex].papers
      } else {
        return []
      }
    },
    subjectIntro() {
      if (this.tabs[this.tabIndex]) {
        return this.tabs[this.tabIndex]["intro"]
      } else {
        return ""
      }
    },
  },

  async mounted() {
    await Promise.all([this.getAuditPaper(), this.getSubject()])
  },

  methods: {
    /** 获取科目信息 */
    async getSubject() {
      let Subject = new wx.BaaS.TableObject("subject")
      uni.showLoading()
      let subjects = await Subject.orderBy("index").find()
      subjects = subjects.data.objects
      this.tabs = subjects.map((item, index) => {
        return {
          name: index,
          label: item.name,
          intro: item.intro,
          id: item.id,
          papers: [],
          num: 1,
          y: 0,
          curPageLen: 0,
          hasNext: true,
        }
      })
      uni.hideLoading()
      if (this.tabs.length !== 0) {
        this.upCallback()
        this.$nextTick(() => {
          setTimeout(() => {
            this.$_getOffect("#intro").then((res) => {
              this.tabTop = (res.top + 10) * 2
            })
          })
        }, 0)
      }
    },

    /** 获取已审核试卷 */
    async getAuditPaper() {
      let UserAudit = new wx.BaaS.TableObject("user_audit")
      let query = new wx.BaaS.Query()
      query.compare("status", "=", 1)
      const res = await UserAudit.expand("paper")
        .setQuery(query)
        .orderBy(["status", "-created_at"])
        .find()
      auditPaper = res.data.objects.map((item) => {
        return item.paper.id
      })
    },

    /** 根据科目获取试卷 */
    async getPapers({ size, current, subject }) {
      let Paper = new wx.BaaS.TableObject("question_paper")
      let Subject = new wx.BaaS.TableObject("subject")

      let selectSubject = Subject.getWithoutData(subject.id)
      let Query = new wx.BaaS.Query()
      Query.compare("subjects", "=", selectSubject)

      uni.showLoading()
      let papers = await Paper.setQuery(Query).find()
      uni.hideLoading()
      return papers.data.objects.map((item) => {
        return {
          tags: `${func.join(item.tags)}`,

          ...item,
        }
      })
    },

    /** 切换菜单 */
    onChangeTab(index) {
      // 记录切换前滚动条的位置
      if (!this.preIndex) this.preIndex = 0
      let preTab = this.tabs[this.preIndex]
      preTab.y = this.mescroll.getScrollTop()
      this.preIndex = index
      // 当前菜单的数据
      let curTab = this.tabs[index]

      if (curTab.papers.length == 0) {
        // 没有初始化,则初始化
        this.mescroll.resetUpScroll()
      } else {
        // 初始化过,则恢复之前的列表数据
        this.mescroll.setPageNum(curTab.num + 1) // 恢复当前页码
        this.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext) // 恢复是否有下一页或显示空布局
        this.$nextTick(() => {
          this.mescroll.scrollTo(curTab.y, 0) // 恢复滚动条的位置
        })
      }
    },

    /*下拉刷新的回调 */
    downCallback() {
      this.mescroll.resetUpScroll()
    },

    /*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
    upCallback(page) {
      let { num, curPageLen } = this.tabs[this.tabIndex]
      this.getPapers({
        current: num,
        size: 10,
        subject: this.tabs[this.tabIndex],
      })
        .then((res) => {
          const curPageData = res
          // 当前tab数据
          let curTab = this.tabs[this.tabIndex]
          // 设置列表数据
          if (curTab.num == 1) curTab.papers = [] //如果是第一页需手动制空列表
          curTab.papers = curTab.papers.concat(curPageData) //追加新数据
          curTab.num = curTab.num++ // 页码
          curTab.curPageLen = curPageData.length // 当前页长
          curTab.hasNext = this.mescroll.optUp.hasNext // 是否还有下一页

          // 需先隐藏加载状态
          this.mescroll.endSuccess(curPageData.length)
        })
        .catch((err) => {
          //联网失败, 结束加载
          this.mescroll.endErr()
        })
    },

    /* 跳转试卷详情页 */
    onClickPaper(paper) {
      selectPaper = paper
      if (paper.isVip && !auditPaper.includes(paper.id)) {
        this.isShowVip = true
        this.setMessage()
      } else {
        uni.navigateTo({
          url: `/pages/question/index?id=${paper.id}&title=${paper.title}&timing=${paper.timing}`,
        })
      }
    },

    /** 订阅消息 */
    setMessage() {
      let id = null
      //#ifdef MP-WEIXIN
      id = wxMessageId
      return new Promise((resolve, reject) => {
        wx.requestSubscribeMessage({
          tmplIds: [id],
          success: (res) => {
            // 用户在真机上同意上报订阅消息
            let subscription = []
            if (res[id] === "accept") {
              subscription.push({
                template_id: id,
                subscription_type: "once",
              })
            }
            resolve()
            wx.BaaS.subscribeMessage({ subscription })
          },
          fail: (err) => {
            reject()
            uni.showToast({ title: "好吧~", icon: "none" })
          },
        })
      })
      //#endif
      //#ifdef MP-QQ
      id = qqMessageId
      return new Promise((resolve, reject) => {
        qq.subscribeAppMsg({
          tmplIds: [id],
          success: (res) => {
            // 用户在真机上同意上报订阅消息
            let subscription = []
            if (res[id] === "accept") {
              subscription.push({
                template_id: id,
                subscription_type: "once",
              })
            }
            resolve()
            qq.BaaS.subscribeMessage({ subscription })
          },
          fail: (err) => {
            reject()
            uni.showToast({ title: "好吧~", icon: "none" })
          },
        })
      })
      //#endif
    },

    /** 点击审核 */
    async onClickAudit() {
      let UserAudit = new wx.BaaS.TableObject("user_audit")
      let QuestionPaper = new wx.BaaS.TableObject("question_paper")
      let questionPaper = QuestionPaper.getWithoutData(selectPaper.id)

      let query = new wx.BaaS.Query()
      query.compare("status", "=", 0)
      query.compare("paper", "=", questionPaper)

      const count = await UserAudit.setQuery(query).count()
      if (count === 0) {
        let MyRecord = UserAudit.create()
        MyRecord.set("status", 0)
        MyRecord.set("username", this.userInfo.nickname)
        MyRecord.set("paper", questionPaper)
        const ResultRes = await MyRecord.save()

        uni.showToast({
          title: "已发送申请!",
        })
      } else {
        uni.showToast({
          title: "等待审核中...",
          icon: "none",
        })
      }
    },

    /** 获取节点信息 */
    async $_getOffect(selector) {
      const getContentItem = (s) =>
        new Promise((resolve, reject) => {
          uni
            .createSelectorQuery()
            .in(this)
            .select(s)
            .boundingClientRect((data) => resolve(data))
            .exec()
        })
      return getContentItem(selector)
    },
  },
}
</script>

<style lang="scss"></style>
